/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Error.h"
#include <WinSock2.h>

/* Max length of error string */
#ifndef _UGAME_MAX_ERROR_STRING_SIZE
#define _UGAME_MAX_ERROR_STRING_SIZE    0x1000
#endif /* _UGAME_MAX_ERROR_STRING_SIZE */

namespace UGame {
namespace System {

    static const char* GetErrorMessage(int _Code, char* _Dest, std::size_t _Size)
    {
        char* _Message = NULL;
        FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER 
            | FORMAT_MESSAGE_FROM_SYSTEM 
            | FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL, _Code,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPSTR)&_Message, 0, NULL);
        _snprintf_s(_Dest, _Size, _TRUNCATE, "%s", _Message);
        LocalFree(_Message);
        return _Dest;
    }

    int GetLastError(void)
    {
        return int(::GetLastError());
    }

    int GetLastNetError(void)
    {
        return int(::WSAGetLastError());
    }

    const char* GetErrorString(char* _Dest, std::size_t _Size, int _Code)
    {
        return GetErrorMessage(_Code, _Dest, _Size);
    }

    const char* GetErrorString(std::string &_Dest, int _Code)
    {
        char _Message[_UGAME_MAX_ERROR_STRING_SIZE];
        _Dest = GetErrorMessage(_Code, _Message, sizeof(_Message));
        return _Dest.c_str();
    }

    const std::string GetErrorString(int _Code)
    {
        char _Message[_UGAME_MAX_ERROR_STRING_SIZE];
        GetErrorMessage(_Code, _Message, sizeof(_Message));
        return std::string(_Message);
    }

}}